#! /usr/bin/env python
#coding=utf-8
import wx
import config
import chardet
import transform
import OptionDialog
import AboutDialog
import images

class mainFrame(wx.Frame):
    def __init__(self, title):
        #get config
        self.config = config.MainFrameConfig()
        self.fontConfig = config.FontConfig()
        
        #transform engine
        self.trans = transform.transform()
        
        #init main frame
        wx.Frame.__init__(self, None, -1, title = title, \
                          pos = (self.config['top'], self.config['left']), \
                          size = (self.config['width'], self.config['height']), \
                          style = wx.DEFAULT_FRAME_STYLE)
        
        self.SetIcon(wx.Icon('v.ico', wx.BITMAP_TYPE_ICO))
        #self.SetIcon(images.VICON.GetIcon())
        
        self.Bind(wx.EVT_CLOSE, self.OnClose)
        self.Bind(wx.EVT_SIZE, self.OnSize)
        self.Bind(wx.EVT_MOVE, self.OnMove)

        #init toolbar
        tb = self.CreateToolBar()
        tb.AddTool( 1, images.OPEN.GetBitmap(), shortHelpString = u'打开')
        self.Bind( wx.EVT_TOOL, self.OnOpenClick, id = 1)
        tb.AddTool( 2, images.SAVE.GetBitmap(), shortHelpString = u'保存图片')
        self.Bind( wx.EVT_TOOL, self.OnSaveClick, id = 2)
        tb.AddTool( 3, images.CONFIG.GetBitmap(), shortHelpString = u'选项')
        self.Bind( wx.EVT_TOOL, self.OnOptionClick, id = 3)
        tb.AddTool( 4, images.V.GetBitmap(), shortHelpString = u'关于')
        self.Bind( wx.EVT_TOOL, self.OnAboutClick, id = 4)
        tb.Realize()
        
        #init font
        font = wx.Font(family = wx.DEFAULT, face = self.fontConfig['face'], pointSize = self.fontConfig['size'], style = self.fontConfig['style'], weight = self.fontConfig['weight'])
        
        #init 2 edits
        self.srcEdt = wx.TextCtrl(self, 10, style = wx.TE_MULTILINE | wx.HSCROLL)
        self.srcEdt.SetFont(font)
        self.srcEdt.Bind(wx.EVT_TEXT, self.OnText)
        self.srcEdt.Bind(wx.EVT_KEY_UP, self.OnKeyUp)
        
        self.destEdt = wx.TextCtrl(self, 11, style = wx.TE_MULTILINE | wx.HSCROLL | wx.TE_READONLY)
        self.destEdt.SetFont(font)
        self.destEdt.Bind(wx.EVT_KEY_UP, self.OnKeyUp)
        
        #init sizer
        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(self.srcEdt, flag=wx.EXPAND, proportion = 1)
        sizer.Add(self.destEdt, flag=wx.EXPAND, proportion = 1)
        self.SetSizer(sizer)
        
        #save the frame info
        self.top, self.left = self.GetPosition()
        self.width, self.height = self.GetSize()
        
        #need max?
        if self.config['max']:
            self.Maximize()
    
    def OnSize(self, event):
        if not self.IsMaximized():
            self.width, self.height = self.GetSize()
        event.Skip()
        return True
    
    def OnMove(self, event):
        if not self.IsMaximized():
             self.top, self.left = self.GetPosition()
        event.Skip()
    
    def OnClose(self, event):
        self.config['top'] = self.top
        self.config['left'] = self.left
        self.config['width'] = self.width
        self.config['height'] = self.height
        self.config['max'] = self.IsMaximized()

        self.config.write()
        
        self.Destroy()
        
    def OnText(self, event):
        self.destEdt.SetValue(self.trans.trans((event.GetString())))
        
    def OnOpenClick(self, event):
        wildcard = u"文本文档 (*.txt)|*.txt|" \
                   u"所有文件 (*.*)|*.*"
        dialog = wx.FileDialog(self, u"打开", "",
                     "", wildcard, wx.OPEN|wx.FILE_MUST_EXIST)
        if dialog.ShowModal() == wx.ID_OK:
            #读取文件
            f = file(dialog.GetPath(), 'r')
            string = f.read()
            f.close()
            #转码
            encoding = chardet.detect(string)['encoding']
            try:
                string = string.decode(encoding)
            except UnicodeDecodeError, detail:
                wx.MessageBox(unicode(detail), u'错误', wx.OK| wx.ICON_ERROR, self)
            #写入srcEdt
            self.srcEdt.SetValue(string)

        dialog.Destroy()

    def OnOptionClick(self, event):
        dlg = OptionDialog.optionDialog(self)
        dlg.Center()
        if dlg.ShowModal() == wx.ID_OK:
            del self.trans
            self.trans = transform.transform()
            self.destEdt.SetValue(self.trans.trans(self.srcEdt.GetValue()))
            
            font = dlg.modeText.GetFont()
            self.srcEdt.SetFont(font)
            self.destEdt.SetFont(font)
            
        dlg.Destroy()
    
    def OnAboutClick(self, event):
        dlg = AboutDialog.aboutDialog(self)
        dlg.Center()
        dlg.ShowModal()
        dlg.Destroy()
        
    def OnKeyUp(self, event):
        if event.ControlDown() and event.GetKeyCode() == ord('A'):
            event.GetEventObject().SetSelection(-1, -1)
    
    def OnSaveClick(self, event):
        wildcard = 'PNG (*.png)|*.png|'\
                    'JPG (*.jpg)|*.jpg|'\
                    'Bitmap (*.bmp)|*.bmp'
        dlg = wx.FileDialog(self, u'保存', '', '', wildcard, wx.FD_SAVE|wx.FD_OVERWRITE_PROMPT)
        if dlg.ShowModal() == wx.ID_OK:
            memory = wx.MemoryDC()
            memory.SetFont(self.destEdt.GetFont())
            texts = self.destEdt.GetValue().split("\n")
            width, height = 0, 0
            for line in texts:
                w, h = memory.GetTextExtent(line)
                width = max(width, w)
                height += h
            print width, height
            bmp = wx.EmptyBitmap(width, height)
            memory.SelectObject(bmp)
            memory.SetTextBackground(self.destEdt.GetBackgroundColour())
            memory.SetTextForeground(self.destEdt.GetForegroundColour())
            memory.Clear()
            y = 0
            for line in texts:
                memory.DrawText(line, 0, y)
                y += memory.GetTextExtent(line)[1]
            memory.SelectObject(wx.NullBitmap)
            
            path = dlg.GetPath()
            ext = path[-3:].upper()
            type = 0
            if ext == 'PNG':
                type = wx.BITMAP_TYPE_PNG
            elif ext == 'BMP':
                type = wx.BITMAP_TYPE_BMP
            elif ext == 'JPG':
                type = wx.BITMAP_TYPE_JPEG
            
            bmp.SaveFile(path, type)
        
        dlg.Destroy()